package com.grep.extra.factory.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

import com.grep.base.servlet.BaseSevlet;


public class FileLoaderUtil {
	
	private static Logger logger = LoggerFactory.getLogger(FileLoaderUtil.class);  
	
	/**
	 * 获取配置参数
	 * @param context
	 * @return
	 */
	public static Map<String,String > getServerConfigPara(ServletContext context){
		Map<String,String > map = new HashMap<String,String>() ;
		if(context!=null){
			Enumeration enu  = context.getInitParameterNames() ;
			while(enu.hasMoreElements()){
				Object obj = enu.nextElement() ;
				if(obj != null){
					map.put(obj.toString().trim().toLowerCase(),context.getInitParameter(obj.toString()) ) ;
				}
			}
		}
		return map ;
	}
	
	/**
	 *  获取数据库配置属性
	 * @param filepath  数据库配置文件
	 * @return
	 */
	public static Properties loadDatabaseProperties(String filepath){
		//获取c3p0配置
		logger.info("[read config] start read dbconfig.") ;
		InputStream in = BaseSevlet.class.getClassLoader().getResourceAsStream(filepath);
		Properties p= new Properties();
		try {
			p.load(in) ;
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.info("[read config] read dbconfig end.") ;
		return p ;
	}
	
	/**
	 * 重设slf4j配置
	 * @param filepath slf4j配置文件路径
	 */
	public static void resetLogProperties(String filepath){
		//重设slf4j配置
		LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); 
		try { 
			JoranConfigurator configurator = new JoranConfigurator(); 
			configurator.setContext(context); 
			// Call context.reset() to clear any previous configuration, e.g. default  
			// configuration. For multi-step configuration, omit calling context.reset(). 
		 	context.reset();  
		 	configurator.doConfigure(BaseSevlet.class.getClassLoader().getResourceAsStream(filepath)); 
		} catch (JoranException je) { 
			je.printStackTrace() ;
		} 
		StatusPrinter.printInCaseOfErrorsOrWarnings(context); 
	}

}
